<script lang="ts" setup>
import type { UnwrapRef } from 'vue';
import { Modal, message } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
// import { useRouter } from 'vue-router';
import { useRouter } from 'vue-router';
import type dayjs from 'dayjs';
import month_add from './month/month_add.vue';
import { useDownExcel } from './useDownExcel';
import useUserStore from '@/store/modules/user';
import { useMonthHistoryStore } from '@/store/modules/dcp/assessment_indicators/month_history';
// 获取用户信息
const userStore = useUserStore();
const orgName = userStore.userOrgName;
const router = useRouter();

const data = ref<AAPI.Month_Item[]>([]);

const finalizedMonth = ref<string[]>([]);

const loading = ref<boolean>(false);

const allColumns: any = [
  {
    title: '序号',
    dataIndex: 'sequenceNumber',
    key: 'sequenceNumber',
    width: '5%',
    align: 'center',
  },
  {
    title: '简称',
    dataIndex: 'abbreviation',
    key: 'abbreviation',
    width: '8%',
    align: 'center',
  },
  {
    title: '部门',
    dataIndex: 'departmentName',
    key: 'departmentName',
    width: '12%',
    align: 'center',
  },
  {
    title: '公共KPI指标（30分）',
    dataIndex: 'publicKpiScore',
    key: 'publicKpiScore',
    width: '10%',
    align: 'center',
  },
  {
    title: '职能工作考核（30分）',
    dataIndex: 'functionalWorkScore',
    key: 'functionalWorkScore',
    width: '10%',
    align: 'center',
  },
  {
    title: 'GS考核（30分）',
    dataIndex: 'gsScore',
    key: 'gsScore',
    width: '10%',
    align: 'center',
  },
  {
    title: '党支部堡垒指数考核',
    dataIndex: 'partyBranchIndex',
    key: 'partyBranchIndex',
    width: '10%',
    align: 'center',
  },
  {
    title: '倒三角支撑（10分）',
    dataIndex: 'reverseSupportScore',
    key: 'reverseSupportScore',
    width: '10%',
    align: 'center',
  },
  {
    title: '合计',
    dataIndex: 'totalScore',
    key: 'totalScore',
    width: '10%',
    align: 'center',
  },
  {
    title: '排名',
    dataIndex: 'ranking',
    key: 'ranking',
    width: '5%',
    align: 'center',
    fixed: 'right',
    sorter: (a: any, b: any) => Number(a.ranking) - Number(b.ranking),
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'lastColumn',
    width: '10%',
    align: 'center',
    fixed: 'right',
  },
];
const { auth } = useAuth();
function showRoleColumn() {
  return auth([
    'a_i_edit',
  ]);
}
const columns: any = computed(() => {
  return allColumns.filter((column: any) => {
    const flag = showRoleColumn();
    if (!flag && column.title === '操作') {
      return false;
    }
    return true;
  });
});
// 获取数据
async function getData() {
  loading.value = true;
  await getMonthList().then((res: any) => {
    data.value = res.data;
  }).catch(() => {
    message.error('数据获取失败！');
  })
    .finally(() => {
      loading.value = false;
    });
}

onMounted(() => {
  if (orgName === '') {
    getData();
  }
  else {
    router.push({ name: 'assessmentIndicatorsKPIDetails', query: { departmentName: orgName } });
  }
});

// 跳转
function linkObject(record: any) {
  return { name: 'assessmentIndicatorsKPIDetails', query: { departmentName: record.departmentName } };
}

// 新增
const visible = ref<boolean>(false);

function add() {
  getVisible();
}

function getVisible() {
  visible.value = !visible.value;
  getData();
}

// 重新计算
async function getCalculate() {
  const item = {};
  await getMonthCalculate(item).then(() => {
    getData();
  });
}

// 搜索
const value = ref<string>('');
async function onSearch(searchValue: string) {
  await getMonthSearch({ departmentName: searchValue }).then((res: any) => {
    message.success('搜索成功!');
    data.value = res.data;
  });
}

// 编辑和删除
async function deleteMonth(id: number) {
  await deleteMonthDetails(id).then(() => {
    getCalculate();
    message.success('删除成功!');
  });
}

const editableData: UnwrapRef<Record<string, any>> = reactive({});

function edit(id: number) {
  editableData[id] = cloneDeep(data?.value?.filter((item: AAPI.Month_Item) => id === item.sequenceNumber)[0]);
}

async function save(id: number) {
  const newData = Object.assign(data?.value?.filter((item: AAPI.Month_Item) => id === item.sequenceNumber)[0], editableData[id]);
  const updateDate = {
    sequenceNumber: newData.sequenceNumber,
    abbreviation: newData.abbreviation,
    departmentName: newData.departmentName,
    publicKpiScore: newData.publicKpiScore,
    functionalWorkScore: newData.functionalWorkScore,
    gsScore: newData.gsScore,
    partyBranchIndex: newData.partyBranchIndex,
    reverseSupportScore: newData.reverseSupportScore,
    totalScore: newData.totalScore,
    ranking: newData.ranking,
  };
  await getEditMonth(updateDate).then(() => {
    message.success('修改成功!');
    getCalculate();
  });
  delete editableData[id];
}

function cancel(id: number) {
  delete editableData[id];
}

async function onDelete(sequenceNumber: number) {
  Modal.confirm({
    title: () => '确定要删除吗？',
    okText: () => '是的',
    okType: 'danger',
    cancelText: () => '取消',
    onOk() {
      data.value = data.value.filter((item: AAPI.Month_Item) => item.sequenceNumber !== sequenceNumber);
      deleteMonth(sequenceNumber);
    },
  });
}

// 日期
const datePicker = ref<any>(null);

function changeTime() {
  nextTick(() => {
    if (datePicker.value) {
      datePicker.value.blur();
    }
  });
}

function getCurrentYearMonth(): string {
  // 获取当前年月
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  return `${year}年${month}月`;
}
const year = ref<any>(getCurrentYearMonth());
const yearMonth = ref<any[]>();
async function getYearMonth() {
  await useMonthHistoryStore().getMonthList();
  yearMonth.value = useMonthHistoryStore().monthList;
}

// 定稿
async function finalizeData() {
  if (!year.value) {
    message.error('请选择月份！');
    return;
  }

  const currentYearMonth = year.value.replace(/年/g, '').replace(/月/g, '');
  // 检查当前月份是否已被定稿
  if (finalizedMonth.value.includes(currentYearMonth)) {
    message.error('当前月份已定稿');
    return;
  }

  if (data.value.length === 0) {
    message.error('没有数据可定稿！');
    return;
  }

  try {
    await addHistory<any, any>(year.value, data.value);
    message.success('定稿成功！');
    data.value = [];
    // 将定稿的月份添加到数组中
    finalizedMonth.value.push(currentYearMonth);
  }
  catch (error) {
    message.error('定稿失败！');
  }
}

// function disabledDate(current: dayjs.Dayjs) {
//   const currentYearMonth = `${current.year()}${(`0${current.month() + 1}`).slice(-2)}`;
//   let flag = false;
//   if (yearMonth.value) {
//     for (let i = 0; i < yearMonth.value.length; i++) {
//       const yearMonthDate = yearMonth.value[i].yearMonth.replace(/年/g, '').replace(/月/g, '').replace(/^(\d{4})(\d)$/, (_: any, year: any, month: string) => `${year}${month.padStart(2, '0')}`);
//       if (currentYearMonth === yearMonthDate) {
//         flag = true;
//       }
//     }
//   }
//   return flag;
// }

function disabledDate(current: dayjs.Dayjs) {
  const currentYearMonth = current.format('YYYYMM');
  // 检查当前月份是否已被定稿
  return finalizedMonth.value.includes(currentYearMonth);
}

onMounted(async () => {
  await getYearMonth();
});
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            部门kpi汇总
          </div>
          <a-button type="link" @click="$router.push('/assessment_indicators/kpi/history')">
            历史记录
          </a-button>
          <a-input-search
            v-model:value="value" placeholder="请输入部门名称" enter-button style="width: 200px;"
            @search="onSearch"
          />
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <div>
            <a-date-picker
              ref="datePicker" v-model:value="year" picker="month" value-format="YYYY年MM月"
              format="YYYY年MM月" :bordered="false" :allow-clear="false" input-read-only :disabled-date="disabledDate"
              @change="changeTime"
            >
              <template #suffixIcon />
            </a-date-picker>
          </div>
          <a-button type="primary" @click="finalizeData">
            定稿
          </a-button>
          <a-button v-auth="'a_i_add'" type="primary" @click="add">
            新增
          </a-button>
          <!-- <a-button type="primary" @click="newExcel">
            新建表
          </a-button> -->
          <a-button type="primary" @click="useDownExcel().downMohthExcel()">
            导出为excel
          </a-button>
        </a-space>
      </div>
    </div>
    <month_add v-if="visible" class="index-add" :visible="visible" :get-visible="getVisible" />
    <div class="content">
      <a-table
        v-if="data.length > 0" :columns="columns" :data-source="data" row-key="id" :scroll="{ x: 1800 }"
        class="m-table" :loading="loading" :pagination="false"
      >
        <template #bodyCell="{ column, text, record }">
          <template
            v-if="['publicKpiScore', 'functionalWorkScore', 'gsScore', 'partyBranchIndex', 'reverseSupportScore'].includes(column.dataIndex as string)"
          >
            <div>
              <a-input
                v-if="editableData[record.sequenceNumber]"
                v-model:value="editableData[record.sequenceNumber][column.dataIndex as string]"
                style="margin: -5px 0;"
              />
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <template v-if="column.dataIndex === 'departmentName'">
            <RouterLink :to="linkObject(record)">
              {{ text }}
            </RouterLink>
          </template>
          <template v-if="column.dataIndex === 'operation'">
            <div class="editable-row-operations">
              <span v-if="editableData[record.sequenceNumber]">
                <a-typography-link @click="save(record.sequenceNumber)">保存</a-typography-link>
                <a @click="cancel(record.sequenceNumber)">取消</a>
              </span>
              <span v-else>
                <a-space>
                  <a @click="edit(record.sequenceNumber)">编辑</a>
                  <a v-if="data.length" @click="onDelete(record.sequenceNumber)">删除</a>
                </a-space>
              </span>
            </div>
          </template>
        </template>
      </a-table>
    </div>
  </PubPageMain>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;
  overflow: auto;

  .header {
    position: sticky;
    top: 0;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    background-color: #fff;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .content {
    display: flex;
    flex: 1;
    flex-direction: column;
    width: 100%;
    height: 95%;
    overflow: auto;
    overflow-y: auto;
    .m-table {
      flex-grow: 1;
      height: 100%;
      max-height: 100%;
      padding: 10px;
    }
  }
}

.editable-row-operations a {
  margin-right: 8px;
}
</style>
